# Copyright 2015 gRPC authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""The Python implementation of the GRPC helloworld.Greeter server."""

from concurrent import futures
import logging

import os
import sys
grpc_protos_path = os.path.join(os.path.abspath(os.path.dirname(__file__)), "api")
sys.path.insert(1, grpc_protos_path)

import grpc
from api.protos.tictactoe_grpc_pb2 import HelloReply, InitReply, PlayReply
from api.protos.tictactoe_grpc_pb2_grpc import GreeterServicer, add_GreeterServicer_to_server
from game_content import GameContent


class Greeter(GreeterServicer):
    def __init__(self):
        self.game_list = {}

    def SayHello(self, request, context):
        return HelloReply(message='Hello, %s!' % request.name)

    def init_game(self, request, context):
        game_id = int(request.id)
        if game_id in self.game_list:
            return InitReply(result=False)
        self.game_list[game_id] = GameContent()
        return InitReply(result=True)

    def refresh_checkerboard(self, request, context):
        game_id = int(request.id)
        position = int(request.position)
        self.game_list[game_id].refresh_checkerboard(position)
        return PlayReply(checkerboard=self.game_list[game_id].checkerboard)


def serve():
    port = '50000'
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
    add_GreeterServicer_to_server(Greeter(), server)
    server.add_insecure_port('[::]:' + port)
    server.start()
    print("Server started, listening on " + port)
    server.wait_for_termination()


if __name__ == '__main__':
    logging.basicConfig()
    serve()
